package com.lukebang.service.serviceImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lukebang.constant.CurtainGoodSpecialType;
import com.lukebang.constant.CurtainStructureType;
import com.lukebang.constant.CurtainStyleType;
import com.lukebang.constant.CurtainType;
import com.lukebang.dao.CityCostRuleDAO;
import com.lukebang.dao.GoodDAO;
import com.lukebang.dao.GoodSpecialDAO;
import com.lukebang.pojo.CityCostRule;
import com.lukebang.pojo.Good;
import com.lukebang.pojo.GoodSpecial;
import com.lukebang.service.IGoodService;
import com.lukebang.util.CalculateOneGoodsPrice;
import com.lukebang.util.JsonUtil;
import com.lukebang.util.ClothCurtain.Arith;
import com.lukebang.util.redis.JedisPoolUtils;

import redis.clients.jedis.Jedis;

/**
 * 
 * GoodServiceImpl 上午11:15:57
 * 
 * Copyright zhaocj Inc. All rights reserved. Love ME Like Justin Bieber.
 */
@Service("goodService")
public class GoodServiceImpl implements IGoodService {
	private static Logger logger = LogManager.getLogger(GoodServiceImpl.class.getName());
	@Resource
	private GoodDAO goodDAO;
	@Resource
	private GoodSpecialDAO goodSpecialDAO;
	@Resource
	CityCostRuleDAO cityCostRuleDAO;

	@Override
	public Map<String, Object> selectIndentProductGoodPartsByIndent(Integer offset, Integer limit, String sort,
			String order, Integer indentID, HttpSession session) {
		logger.debug("你好 开始调用本方法");
		Map<String, Object> retMap = new HashMap<String, Object>();
		// 查看该订单的成品帘商品 查询基础信息
		List<Good> goods = goodDAO.selectIndentGoodByIndent(indentID, 1);
		logger.debug("查出的成品链商品有：{}", JsonUtil.toJson(goods));
		List<GoodSpecial> goodSpecials = new ArrayList<GoodSpecial>();
		for (Good good : goods) {
			// 根据good查询出配件信息
			goodSpecials.addAll(goodSpecialDAO.selectGoodSpecialsByGood(good.getGoodsId()));
		}
		retMap.put("productGoodPart", goodSpecials);
		return retMap;
	}

	@Override
	public Map<String, Object> selectIndentClothGoodPartsByIndent(Integer offset, Integer limit, String sort,
			String order, Integer indentID, HttpSession session) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<Good> goods = goodDAO.selectIndentGoodByIndent(indentID, 0);
		logger.debug("查出的布艺帘商品有：{}", JsonUtil.toJson(goods));
		List<GoodSpecial> goodSpecials = new ArrayList<GoodSpecial>();
		for (Good good : goods) {
			goodSpecials.addAll(goodSpecialDAO.selectGoodSpecialsByGood(good.getGoodsId()));
		}
		retMap.put("clothGoodPart", goodSpecials);
		return retMap;
	}

	@Override
	public Map<String, Object> queryIndentGoodPartsByIndent(Integer indentID) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<Good> goods = goodDAO.selectAllIndentGoodByIndent(indentID);
		List<GoodSpecial> goodSpecials = new ArrayList<GoodSpecial>();
		List<Integer> collapseNumbers = new ArrayList<Integer>();
		Map<String, Object> goodSpecialDetailMap = new HashMap<String, Object>();
		for (Good good : goods) {
			good.setCurtainTypeStr(CurtainType.getName(good.getType() + 1));
			// 如果是布艺帘的话 则设置结构信息 和 风格信息
			if (good.getType() == 0) {
				good.setStructureStr(CurtainStructureType.getName(good.getStructure() + 1));
				if (good.getStyle() == 3) {
					if (good.getShadeHead() == 1) {
						good.setStyleStr("帘头款");
					} else {
						good.setStyleStr(CurtainStyleType.getName(good.getStyle() + 1));
					}
				} else if (good.getStyle() == 0) {
					good.setStyleStr(CurtainStyleType.getName(good.getStyle() + 1));
				} else {
					good.setStyleStr("暂无信息");
				}
			}
			List<GoodSpecial> specialsByGood = goodSpecialDAO.selectGoodSpecialsByGood(good.getGoodsId());
			for (GoodSpecial goodSpecial : specialsByGood) {
				goodSpecialDetailMap = goodDAO.selectPartsOfGoodSpecialByGoodID(goodSpecial.getAccId());
				goodSpecial.setGoodSpecialTypeStr(CurtainGoodSpecialType.getName(goodSpecial.getType() + 1));
				// 如果不是成品尺寸
				if (goodSpecial.getType() != 3) {
					goodSpecial.setSaleNumber(Double.valueOf((goodSpecialDetailMap.get("saleNumber").toString())));
				}
				// 如果不是帘头尺寸的话
				if (goodSpecial.getType() != 2 && goodSpecial.getType() != 3) {
					goodSpecial.setPanzhuangfangshi(goodSpecialDetailMap.get("panzhuangfangshi").toString());
				}
				// 如果不是帘头尺寸的话
				if (goodSpecial.getType() != 2 && goodSpecial.getType() != 3) {
					goodSpecial.setPinstallSite(goodSpecialDetailMap.get("pinstallSite").toString());
				}
				if (goodSpecial.getGoodForRoom() == null || goodSpecial.getGoodForRoom() == "") {
					goodSpecial.setGoodForRoom(good.getOtherRoom());
				}
				goodSpecial.setGood(good);
			}
			collapseNumbers.add(specialsByGood.size());
			goodSpecials.addAll(specialsByGood);
		}
		retMap.put("goodPart", goodSpecials);
		retMap.put("collapseNumbers", collapseNumbers);
		return retMap;
	}

	@Override
	public Map<String, Object> selectForRefreshInstallIndentGoods(String fakeIndentID, String cityCodeStr) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		// 存放当前Good的基本信息
		Good good = new Good();
		// 获取所有的商品的ID
		Jedis jedis = JedisPoolUtils.getJedis();
		jedis.select(2);
		List<String> lrange = jedis.lrange(fakeIndentID, 0, -1);
		List<GoodSpecial> retGoodSpecials = new ArrayList<GoodSpecial>();
		List<Integer> collapseNumbers = new ArrayList<Integer>();
		for (String fakeGoodID : lrange) {
			Integer collapseNumber = 0;
			String goodMapStr = jedis.get(fakeIndentID + "_" + fakeGoodID);
			logger.debug("查询出来的商品的信息：{}", goodMapStr);
			JSONObject goodMapJSON = JSON.parseObject(goodMapStr);
			
			String finishShade = goodMapJSON.get("finishShade")== null ? null: goodMapJSON.get("finishShade").toString();
			String clothShade = goodMapJSON.get("clothShade") == null ? null : goodMapJSON.get("clothShade").toString();
			String yarnShade = goodMapJSON.get("yarnShade") == null ? null : goodMapJSON.get("yarnShade").toString();
			String headShade = goodMapJSON.get("headShade") == null ? null : goodMapJSON.get("headShade").toString();
			good = JSON.parseObject(goodMapJSON.get("currentGood").toString(), Good.class);
			System.out.println("======================start============================");
			
			Double indentPrice = new CalculateOneGoodsPrice().calculateOneGoods(cityCostRuleDAO, good, finishShade,
					clothShade, yarnShade, headShade, cityCodeStr, 1);
			good.setGoodsId(Integer.valueOf(fakeGoodID));
			good.setInstallPrice(indentPrice);
			
			System.out.println("======================end============================");
			good.setCurtainTypeStr(CurtainType.getName(good.getType() + 1));
			// 如果是布艺帘的话 则设置结构信息 和 风格信息
			if (good.getType() == 0) {
				good.setStructureStr(CurtainStructureType.getName(good.getStructure() + 1));
				good.setStyleStr(CurtainStyleType.getName(good.getStyle() + 1));
			}
			if (!"".equals(finishShade) && null != finishShade) {
				List<GoodSpecial> finishShadeGoodSpecial = JSON.parseArray(finishShade, GoodSpecial.class);
				if(finishShadeGoodSpecial.size()>0){
					for (GoodSpecial goodSpecial : finishShadeGoodSpecial) {
						goodSpecial.setGood(good);
						goodSpecial.setType(3);
						goodSpecial.setGoodSpecialTypeStr(CurtainGoodSpecialType.ProductSize.getName());
	//				goodSpecial.setGoodForRoom(roomStr);
					}
					collapseNumber = collapseNumber + finishShadeGoodSpecial.size();
					retGoodSpecials.addAll(finishShadeGoodSpecial);
				}
			}
			if (!"".equals(clothShade) && null != clothShade) {
				List<GoodSpecial> clothShadeGoodSpecial = JSON.parseArray(clothShade, GoodSpecial.class);
				if(clothShadeGoodSpecial.size()>0){
					for (GoodSpecial goodSpecial : clothShadeGoodSpecial) {
						goodSpecial.setGood(good);
						goodSpecial.setType(0);
						goodSpecial.setGoodSpecialTypeStr(CurtainGoodSpecialType.ClothSize.getName());
	//				goodSpecial.setGoodForRoom(roomStr);
					}
					collapseNumber = collapseNumber + clothShadeGoodSpecial.size();
					retGoodSpecials.addAll(clothShadeGoodSpecial);
				}
			}
			if (!"".equals(headShade) && null != headShade) {
				List<GoodSpecial> headShadeGoodSpecial = JSON.parseArray(headShade, GoodSpecial.class);
				if(headShadeGoodSpecial.size()>0){
					for (GoodSpecial goodSpecial : headShadeGoodSpecial) {
						goodSpecial.setGood(good);
						goodSpecial.setType(2);
						goodSpecial.setGoodSpecialTypeStr(CurtainGoodSpecialType.ValanceSize.getName());
	//				goodSpecial.setGoodForRoom(roomStr);
					}
					collapseNumber = collapseNumber + headShadeGoodSpecial.size();
					retGoodSpecials.addAll(headShadeGoodSpecial);
				}
			}
			if (!"".equals(yarnShade) && null != yarnShade) {
				List<GoodSpecial> yarnShadeGoodSpecial = JSON.parseArray(yarnShade, GoodSpecial.class);
				if(yarnShadeGoodSpecial.size()>0){
					for (GoodSpecial goodSpecial : yarnShadeGoodSpecial) {
						goodSpecial.setGood(good);
						goodSpecial.setType(1);
						goodSpecial.setGoodSpecialTypeStr(CurtainGoodSpecialType.YarnSize.getName());
	//				goodSpecial.setGoodForRoom(roomStr);
					}
					collapseNumber = collapseNumber + yarnShadeGoodSpecial.size();
					retGoodSpecials.addAll(yarnShadeGoodSpecial);
				}
			}
			collapseNumbers.add(collapseNumber);
		}
		JedisPoolUtils.close(jedis);
		retMap.put("goodPart", retGoodSpecials);
		retMap.put("collapseNumbers", collapseNumbers);
		return retMap;
	}

	/**
	 * 计算安装订单下的某一goods的商品价格 xiaGuanghui 2017年6月9日 上午10:41:41
	 * 
	 * @param good
	 *            需要计算的good
	 * @param city
	 *            安装订单的城市
	 * @return
	 */
	public Map<String, Object> calculateInstallIndent(Good good, String city) {
		Map<String, Object> returnMap = new HashMap<>();
		// 该goods对应的商家和工人的价格分别为merchantsPrice,indentPrice
		Double merchantsPrice = 0.00;
		Double indentPrice = 0.00;
		// 判断该good是属于成品帘type=1还是布艺帘type=0
		if (good.getType() !=null && good.getType() == 0) {
			// 判断是属于布艺帘中的单布structure=0还是单纱structure=1又或者属于布纱双层structure=2
			if (good.getStructure() !=null && good.getStructure() == 0) {
				// 获取该单布旗下的所有goods_special的accId对应的商品
				List<Map<String, Object>> buPeiList = goodDAO.selectGoodByAccId(good.getGoodsId(), 0);
				// 遍历集合
				for (int index1 = 0; index1 < buPeiList.size(); index1++) {
					// 配件安装方式
					String panzhuangfangshi = (String) buPeiList.get(index1).get("panzhuangfangshi");
					// 计算布配件安装费 根据配件类型还有地域获得计算方式
					Map<String, Object> bupeijian = new HashMap<>();
					bupeijian.put("type", (String) buPeiList.get(index1).get("accessoriesType"));
					bupeijian.put("cityCode", city);
					Double[] price = getPrice(buPeiList, index1, merchantsPrice, indentPrice, bupeijian, true);
					merchantsPrice = price[0];
					indentPrice = price[1];
					// 判断安装配件只会含有"装单"或"双联码"
					if (panzhuangfangshi.indexOf("装单") > 0) {
						// 判断是否有帘头
						if (good.getShadeHead() !=null && good.getShadeHead() == 1) {
							int goodsIdChild = good.getGoodsId() * 10 + index1;
							List<Map<String, Object>> toupeijain = goodSpecialDAO.selectTouPeiJian(good.getGoodsId(),
									goodsIdChild, 0);
							Map<String, Object> liantoupeijian = new HashMap<>();
							liantoupeijian.put("type", "帘头");
							liantoupeijian.put("cityCode", city);
							Double[] price1 = getPrice(toupeijain, 0, merchantsPrice, indentPrice, liantoupeijian,
									true);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					} else {// 不含有‘装单’ 肯定为双联码 肯定有帘头且按双层计算
							// 判断是否有帘头
						if (good.getShadeHead() !=null && good.getShadeHead() == 1) {// 帘头按照单层计算
							// 获得帘头配件
							int goodsIdChild = good.getGoodsId() * 10 + index1;
							List<Map<String, Object>> toupeijian = goodSpecialDAO.selectTouPeiJian(good.getGoodsId(),
									goodsIdChild, 0);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("cityCode", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, false);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					}
				}
				// 单纱
			} else if (good.getStructure() !=null && good.getStructure() == 1) {
				// 获取纱配件集合
				List<Map<String, Object>> shaPeiList = goodDAO.selectGoodByAccId(good.getGoodsId(), 1);
				for (int index1 = 0; index1 < shaPeiList.size(); index1++) {
					// 配件安装方式
					String panzhuangfangshi = (String) shaPeiList.get(index1).get("panzhuangfangshi");
					// 计算布配件安装费 根据配件类型还有地域获得计算方式
					Map<String, Object> bupeijian = new HashMap<>();
					bupeijian.put("type", (String) shaPeiList.get(index1).get("accessoriesType"));
					bupeijian.put("cityCode", city);
					Double[] price = getPrice(shaPeiList, index1, merchantsPrice, indentPrice, bupeijian, true);
					merchantsPrice = price[0];
					indentPrice = price[1];
					// 判断安装配件只会含有"装单"或"双联码"
					if (panzhuangfangshi.indexOf("装单") > 0) {
						// 判断是否有帘头
						if (good.getShadeHead() !=null && good.getShadeHead() == 1) {
							int goodsIdChild = good.getGoodsId() * 10 + index1;
							List<Map<String, Object>> toupeijain = goodSpecialDAO.selectTouPeiJian(good.getGoodsId(),
									goodsIdChild, 1);
							Map<String, Object> liantoupeijian = new HashMap<>();
							liantoupeijian.put("type", "帘头");
							liantoupeijian.put("cityCode", city);
							Double[] price1 = getPrice(toupeijain, 0, merchantsPrice, indentPrice, liantoupeijian,
									true);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					} else {// 不含有‘装单’ 肯定为双联码 肯定有帘头且按双层计算
							// 判断是否有帘头
						if (good.getShadeHead() !=null && good.getShadeHead() == 1) {// 帘头按照单层计算
							// 获得帘头配件
							int goodsIdChild = good.getGoodsId() * 10 + index1;
							List<Map<String, Object>> toupeijian = goodSpecialDAO.selectTouPeiJian(good.getGoodsId(),
									goodsIdChild, 1);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("cityCode", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, false);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					}
				}

				// 布加纱
			} else if (good.getStructure() !=null && good.getStructure() == 2) {
				// 获取布配件集合(特殊安装有多少个所以要用集合)
				List<Map<String, Object>> buPeiList = goodDAO.selectGoodByAccId(good.getGoodsId(), 0);
				List<Map<String, Object>> shaPeiList = goodDAO.selectGoodByAccId(good.getGoodsId(), 1);
				// 有单独的纱配件说明是布纱单独安装，纱按单层价格计算
				if (shaPeiList != null && shaPeiList.size() > 0) {
					for (int index = 0; index < shaPeiList.size(); index++) {
						// 计算纱配件安装费
						// 根据配件类型还有地域获得计算方式
						Map<String, Object> peijiansha = new HashMap<>();
						peijiansha.put("type", shaPeiList.get(index).get("accessoriesType"));
						peijiansha.put("cityCode", city);
						Double[] price = getPrice(shaPeiList, index, merchantsPrice, indentPrice, peijiansha, true);
						merchantsPrice = price[0];
						indentPrice = price[1];
					}
					// 有纱尺寸时走的逻辑
					for (int index = 0; index < buPeiList.size(); index++) {
						String panzhuangfangshi = (String) buPeiList.get(index).get("panzhuangfangshi");
						// 判断其中包含的字符串
						if (panzhuangfangshi.indexOf("装单") >= 0) {
							// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
							bupeijian.put("cityCode", city);
							// 第一次计价,相当于计算单布安装费
							Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian, true);
							merchantsPrice = price[0];//
							indentPrice = price[1];//
							// 计算帘头配件安装费
							// 判断是否有帘头
							if (good.getShadeHead()!=null && good.getShadeHead() == 1) {// 帘头按照单层计算(布纱双层分开，顶装单安装码，布纱帘全独立安装)
								// 获得帘头配件
								int goodsIdChild = good.getGoodsId() * 10 + index;
								List<Map<String, Object>> toupeijian = goodSpecialDAO
										.selectTouPeiJian(good.getGoodsId(), goodsIdChild, 0);
								Map<String, Object> lianpeijian = new HashMap<>();
								lianpeijian.put("type", "帘头");
								lianpeijian.put("cityCode", city);
								Double[] price2 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
										true);
								merchantsPrice = price2[0];
								indentPrice = price2[1];
							}
						} else if (panzhuangfangshi.indexOf("装双") >= 0) {
							// 证明布纱双层安装
							// 计算布配件安装费
							// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
							bupeijian.put("cityCode", city);
							Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian, true);
							merchantsPrice = price[0];
							indentPrice = price[1];
							// 计算帘头配件安装费
							// 判断是否有帘头
							if (good.getShadeHead() !=null && good.getShadeHead() == 1) {// 帘头按照单层计算
								// 获得帘头配件
								int goodsIdChild = good.getGoodsId() * 10 + index;
								List<Map<String, Object>> toupeijian = goodSpecialDAO
										.selectTouPeiJian(good.getGoodsId(), goodsIdChild, 0);
								Map<String, Object> lianpeijian = new HashMap<>();
								lianpeijian.put("type", "帘头");
								lianpeijian.put("cityCode", city);
								Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
										false);
								merchantsPrice = price1[0];
								indentPrice = price1[1];
							}
						} else if (panzhuangfangshi.indexOf("双联码") >= 0) {
							// 判断布纱安装位置是否一致
							if (good.getInstallCase() == 1) {// 布纱安装情况一致 证明没有帘头
								// 计算布配件安装费
								// 根据配件类型还有地域获得计算方式
								Map<String, Object> bupeijian = new HashMap<>();
								bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
								bupeijian.put("cityCode", city);
								Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian,
										false);
								merchantsPrice = price[0];
								indentPrice = price[1];
							} else {// 布纱安装情况不一致 证明有帘头
									// 证明布+纱单独安装 帘头不单独
									// 计算布配件安装费
									// 根据配件类型还有地域获得计算方式
								Map<String, Object> bupeijian = new HashMap<>();
								bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
								bupeijian.put("cityCode", city);
								Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian,
										true);
								merchantsPrice = price[0];
								indentPrice = price[1];
								// 计算帘头配件安装费
								// 判断是否有帘头
								if (good.getShadeHead() !=null && good.getShadeHead() == 1) {// 帘头按照一体帘头计算
									// 获得帘头配件
									int goodsIdChild = good.getGoodsId() * 10 + index;
									List<Map<String, Object>> toupeijian = goodSpecialDAO
											.selectTouPeiJian(good.getGoodsId(), goodsIdChild, 0);
									Map<String, Object> lianpeijian = new HashMap<>();
									lianpeijian.put("type", "帘头");
									lianpeijian.put("cityCode", city);
									Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
											false);
									merchantsPrice = price1[0];
									indentPrice = price1[1];
								}
							}
						} else {// 三联码 这种情况有吗？
								// 证明布+纱双层安装 帘头不单独
								// 计算布配件安装费
								// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
							bupeijian.put("cityCode", city);
							Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian, false);
							merchantsPrice = price[0];
							indentPrice = price[1];
							// 获得帘头配件
							int goodsIdChild = good.getGoodsId() * 10 + index;
							List<Map<String, Object>> toupeijian = goodSpecialDAO.selectTouPeiJian(good.getGoodsId(),
									goodsIdChild, 0);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("cityCode", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, false);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					}

				} else {
					// 没有纱尺寸时走的逻辑
					for (int index = 0; index < buPeiList.size(); index++) {
						String panzhuangfangshi = (String) buPeiList.get(index).get("panzhuangfangshi");
						// 判断其中包含的字符串
						if (panzhuangfangshi.indexOf("装单") >= 0) {//
							// 证明全部单独安装,因为没有纱配件，所有按照
							// 计算布配件安装费
							// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
							bupeijian.put("cityCode", city);
							Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian, true);// 第一次计价，相当于计算单布安装费
							merchantsPrice = price[0];//
							indentPrice = price[1];//
							Double[] price1 = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian, true);// 第二次计价，相当于计算单纱安装费
							merchantsPrice = price1[0];//
							indentPrice = price1[1];//

							// 计算帘头配件安装费
							// 判断是否有帘头
							if (good.getShadeHead() !=null && good.getShadeHead() == 1) {// 帘头按照单层计算(布纱双层分开，顶装单安装码，布纱帘全独立安装)
								// 获得帘头配件
								int goodsIdChild = good.getGoodsId() * 10 + index;
								List<Map<String, Object>> toupeijian = goodSpecialDAO
										.selectTouPeiJian(good.getGoodsId(), goodsIdChild, 0);
								Map<String, Object> lianpeijian = new HashMap<>();
								lianpeijian.put("type", "帘头");
								lianpeijian.put("cityCode", city);
								Double[] price2 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
										true);
								merchantsPrice = price2[0];
								indentPrice = price2[1];
							}
						} else if (panzhuangfangshi.indexOf("装双") >= 0) {
							// 证明布纱双层安装
							// 计算布配件安装费
							// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
							bupeijian.put("cityCode", city);
							Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian, false);
							merchantsPrice = price[0];
							indentPrice = price[1];
							// 计算帘头配件安装费
							// 判断是否有帘头
							if (good.getShadeHead() !=null && good.getShadeHead() == 1) {// 帘头按照独立帘头计算
								// 获得帘头配件
								int goodsIdChild = good.getGoodsId() * 10 + index;
								List<Map<String, Object>> toupeijian = goodSpecialDAO
										.selectTouPeiJian(good.getGoodsId(), goodsIdChild, 0);
								Map<String, Object> lianpeijian = new HashMap<>();
								lianpeijian.put("type", "帘头");
								lianpeijian.put("cityCode", city);
								Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
										true);
								merchantsPrice = price1[0];
								indentPrice = price1[1];
							}
						} else if (panzhuangfangshi.indexOf("双联码") >= 0) {
							// 判断布纱安装位置是否一致
							if (good.getInstallCase() == 1) {// 布纱安装情况一致 证明没有帘头
								// 计算布配件安装费
								// 根据配件类型还有地域获得计算方式
								Map<String, Object> bupeijian = new HashMap<>();
								bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
								bupeijian.put("cityCode", city);
								Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian,
										false);
								merchantsPrice = price[0];
								indentPrice = price[1];
							} else {// 布纱安装情况不一致 证明有帘头
									// 证明布+纱单独安装 帘头不单独
									// 计算布配件安装费
									// 根据配件类型还有地域获得计算方式
								Map<String, Object> bupeijian = new HashMap<>();
								bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
								bupeijian.put("cityCode", city);
								Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian,
										true);
								merchantsPrice = price[0];
								indentPrice = price[1];
								// 计算帘头配件安装费
								// 判断是否有帘头
								if (good.getShadeHead() !=null && good.getShadeHead() == 1) {// 帘头按照一体帘头计算
									// 获得帘头配件
									int goodsIdChild = good.getGoodsId() * 10 + index;
									List<Map<String, Object>> toupeijian = goodSpecialDAO
											.selectTouPeiJian(good.getGoodsId(), goodsIdChild, 0);
									Map<String, Object> lianpeijian = new HashMap<>();
									lianpeijian.put("type", "帘头");
									lianpeijian.put("cityCode", city);
									Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
											false);
									merchantsPrice = price1[0];
									indentPrice = price1[1];
								}
							}
						} else {// 三联码 这种情况有吗？
								// 证明布+纱双层安装 帘头不单独
								// 计算布配件安装费
								// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", buPeiList.get(index).get("accessoriesType"));
							bupeijian.put("cityCode", city);
							Double[] price = getPrice(buPeiList, index, merchantsPrice, indentPrice, bupeijian, false);
							merchantsPrice = price[0];
							indentPrice = price[1];
							// 获得帘头配件
							int goodsIdChild = good.getGoodsId() * 10 + index;
							List<Map<String, Object>> toupeijian = goodSpecialDAO.selectTouPeiJian(good.getGoodsId(),
									goodsIdChild, 0);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("cityCode", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, false);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					}
				}

			}
			// 成品帘
		} else if (good.getType() !=null && good.getType() == 1) {
			// 根据市获取价格
			// 根据goodsId获取所有Goods_special表中goodsId为当前goodsId的数据
			List<Map<String, Object>> finishedList = goodSpecialDAO.selectFinishedCurtains(good.getGoodsId());
			Map<String, Object> peijian = new HashMap<>();
			peijian.put("type", "成品帘");
			peijian.put("cityCode", city);
			peijian.put("territoryType", 1);// 代表商家
			CityCostRule anzhuang = cityCostRuleDAO.selectAPrice(peijian);// 商家价格
			peijian.put("territoryType", 0);// 代表工人
			CityCostRule anzhuangGR = cityCostRuleDAO.selectAPrice(peijian);// 工人价格
			for (Map<String, Object> map : finishedList) {
				// 判断配件米数与基础米数比较,（应该是两种情况，{高度3米内}{高度3米外}）{商家价格计算}
				double heightBasisMeter = anzhuang.getHeightBasisMeter();// 基础高
				double height = (Double) map.get("high");// 计费高度
				double basePrice = anzhuang.getSingle();// 基础价格，便于宽度或高度超标时累计单价
				if (height > heightBasisMeter) {
					Double reduction = Arith.sub(height, heightBasisMeter);// 高度超标量
					Double chaochu = Arith.mul((Math.ceil(Arith.div(reduction, anzhuang.getHeightBeyondMeter()))),
							anzhuang.getHeightBeyondUnitPrice());
					merchantsPrice = Arith.add(Arith.add(basePrice, chaochu), merchantsPrice);
				} else {
					merchantsPrice = merchantsPrice + basePrice;
				}
				// 工人收到的订单价格
				double heightBasisMeter1 = anzhuangGR.getHeightBasisMeter();// 基础高
				double height1 = (Double) map.get("high");// 计费高度
				double basePrice1 = anzhuangGR.getSingle();// 基础价格，便于宽度或高度超标时累计单价
				if (height1 > heightBasisMeter1) {
					Double reduction1 = Arith.sub(height1, heightBasisMeter1);// 高度超标量
					Double chaochu1 = Arith.mul((Math.ceil(Arith.div(reduction1, anzhuangGR.getHeightBeyondMeter()))),
							anzhuangGR.getHeightBeyondUnitPrice());
					indentPrice = Arith.add(Arith.add(basePrice1, chaochu1), indentPrice);
				} else {
					indentPrice = indentPrice + basePrice1;
				}
			}
		} else {
			returnMap.put("message", false);
			return returnMap;
		}
		// 把安装费存到表中
		Map<String, Object> param = new HashMap<>();
		param.put("goodsId", good.getGoodsId());
		param.put("installPrice", indentPrice);
		goodDAO.updateGoodsInstallPrice(param);
		returnMap.put("merchantsPrice", merchantsPrice);
		returnMap.put("indentPrice", indentPrice);
		return returnMap;
	}

	/**
	 * 用于计算价格 xiaGuanghui 2017年6月9日 下午2:33:48
	 * 
	 * @param peiList
	 * @param index
	 * @param merchantsPrice
	 * @param indentPrice
	 * @param peijian
	 * @param isSingle
	 * @return
	 */
	private Double[] getPrice(List<Map<String, Object>> peiList, int index, Double merchantsPrice, Double indentPrice,
			Map<String, Object> peijian, boolean isSingle) {
		peijian.put("territoryType", 1);// 代表商家
		CityCostRule anzhuang = cityCostRuleDAO.selectAPrice(peijian);// 商家价格
		peijian.put("territoryType", 0);// 代表工人
		CityCostRule anzhuangGR = cityCostRuleDAO.selectAPrice(peijian);// 工人价格
		// 判断配件米数与基础米数比较,（应该是四种情况，宽度4米内{高度3米内}{高度3米外}，宽度4米外{高度3米内}{高度3米外}）
		Double widthBasisMeter=null;
		Double heightBasisMeter=null;
		Double width =null;// 计费宽度
		Double height=null;// 计费高度
		Double[] price = new Double[2];
		if(anzhuang!=null){
			 widthBasisMeter = anzhuang.getWidthBasisMeter();// 基础宽
			 heightBasisMeter = anzhuang.getHeightBasisMeter();// 基础高
		}
		
		if(peiList!=null && peiList.size()>0){
			if(peiList.get(index) != null){
				width =(Double) peiList.get(index).get("saleNumber");
				height = (Double) peiList.get(index).get("high");
			}
		}
		
		// logger.error("===计算价格的list===" + JSONObject.toJSONString(list));
		if(widthBasisMeter !=null &&  heightBasisMeter !=null && width !=null && height !=null){
			if (widthBasisMeter >= width && heightBasisMeter >= height) {// 宽高均在正常范围内,isSingle控制计算单双层价格
				merchantsPrice = Arith.add(merchantsPrice, isSingle ? anzhuang.getSingle() : anzhuang.getDoubleDeck());
				indentPrice = Arith.add(indentPrice, isSingle ? anzhuangGR.getSingle() : anzhuangGR.getDoubleDeck());
			} else if (widthBasisMeter >= width && heightBasisMeter < height) {// 宽正常，高超标
				// 计算商家价格
				merchantsPrice = pricePartOne(anzhuang, height, heightBasisMeter, merchantsPrice, isSingle);
	
				// 计算工人价格(订单价)
				indentPrice = pricePartOne(anzhuangGR, height, heightBasisMeter, indentPrice, isSingle);
	
			} else if (widthBasisMeter < width && heightBasisMeter >= height) {// 宽超标，高正常
				// 计算商家价格
				merchantsPrice = pricePartTwo(anzhuang, width, widthBasisMeter, merchantsPrice, isSingle);
	
				// 计算工人价格(订单价)
				indentPrice = pricePartTwo(anzhuangGR, width, widthBasisMeter, indentPrice, isSingle);
			} else {// 宽超标，高超标
				// 计算商家价格
				merchantsPrice = pricePartThree(anzhuang, width, height, widthBasisMeter, heightBasisMeter, merchantsPrice,
						isSingle);
	
				// 计算工人价格(订单价)
				indentPrice = pricePartThree(anzhuangGR, width, height, widthBasisMeter, heightBasisMeter, indentPrice,
						isSingle);
			}
		}
		price[0] = merchantsPrice;
		price[1] = indentPrice;
		return price;
	}

	// 计算高超标价格
	private double pricePartOne(CityCostRule part, Double height, Double heightBasisMeter, Double price,
			boolean isSingle) {
		double basePrice = isSingle ? part.getSingle() : part.getDoubleDeck();// 基础价格，便于宽度或高度超标时累计单价
		Double reduction = Arith.sub(height, heightBasisMeter);// 高度超标量
		Double chaochu = Arith.mul((Math.ceil(Arith.div(reduction, part.getHeightBeyondMeter()))),
				part.getHeightBeyondUnitPrice());
		price = Arith.add(Arith.add(basePrice, chaochu), price);
		// return Math.max(price, part.getInstallStartingFare());
		return price;
	}

	// 计算宽超标价格
	private double pricePartTwo(CityCostRule part, Double width, Double widthBasisMeter, Double price,
			boolean isSingle) {
		// 计算商家价格
		double basePrice = isSingle ? part.getSingle() : part.getDoubleDeck();// 基础价格，便于宽度或高度超标时累计单价
		Double reduction = Arith.sub(width, widthBasisMeter);// 宽度超标量
		Double chaochu = Arith.mul((Math.ceil(Arith.div(reduction, part.getWidthBeyondMeter()))), basePrice);
		price = Arith.add(Arith.add(basePrice, chaochu), price);
		// return Math.max(price, part.getInstallStartingFare());
		return price;
	}

	// 计算宽高都超标价格
	private double pricePartThree(CityCostRule part, Double width, Double height, Double widthBasisMeter,
			Double heightBasisMeter, Double price, boolean isSingle) {
		// 计算商家价格
		double basePrice = isSingle ? part.getSingle() : part.getDoubleDeck();// 基础价格，便于宽度或高度超标时累计单价
		Double reductions = Arith.sub(height, heightBasisMeter);// 高度超标量 5
		Double reduction = Arith.sub(width, widthBasisMeter);// 宽度超标量 6
		Double chaochus = Arith.mul((Math.ceil(Arith.div(reductions, part.getHeightBeyondMeter()))),
				part.getHeightBeyondUnitPrice());// 100
		Double heightPrice = Arith.add(basePrice, chaochus);// 120
		Double total = Arith.mul((Math.ceil(Arith.div(reduction, part.getWidthBeyondMeter()))) + 1, heightPrice);// 360
		price = Arith.add(total, price);
		// return Math.max(price, part.getInstallStartingFare());
		return price;
	}

	@Override
	public Map<String, Object> selectInstallIndentGoodByIndentID(String indentID) {
		logger.debug("你好 开始调用本方法");
		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, Object> goodSpecialDetailMap = new HashMap<String, Object>();
		// 查询出安装订单的所有商品
		List<Good> goods = goodDAO.selectInstallIndentGoodByIndent(indentID);
		List<GoodSpecial> goodSpecials = new ArrayList<GoodSpecial>();
		List<Integer> collapseNumbers = new ArrayList<Integer>();
		for (Good good : goods) {
			good.setCurtainTypeStr(CurtainType.getName(good.getType() + 1));
			// 如果是布艺帘的话 则设置结构信息 和 风格信息
			if (good.getType() == 0) {
				good.setStructureStr(CurtainStructureType.getName(good.getStructure() + 1));
				good.setStyleStr(CurtainStyleType.getName(good.getStyle() + 1));
			}
			List<GoodSpecial> currentGoodSpecials = goodSpecialDAO.selectGoodSpecialsByGood(good.getGoodsId());
			// 如果是布纱双层 相同位置
			if (good.getInstallCase() != null && good.getInstallCase() == 1) {
				Iterator<GoodSpecial> iterator = currentGoodSpecials.iterator();
				while (iterator.hasNext()) {
					GoodSpecial next = iterator.next();
					// 如果是纱帘尺寸
					if (next.getType() == 1) {
						iterator.remove();
						break;
					}
				}
			}
			for (GoodSpecial goodSpecial : currentGoodSpecials) {
					if(goodSpecial==null) {
						continue;
					}
					goodSpecialDetailMap = goodDAO.selectPartsOfGoodSpecialByGoodID(goodSpecial.getAccId());
					if(goodSpecialDetailMap!=null){
						// 如果不是成品尺寸
						if (goodSpecial.getType() != 3) {
							goodSpecial.setSaleNumber(Double.valueOf((goodSpecialDetailMap.get("saleNumber")==null?"0.0"
									:goodSpecialDetailMap.get("saleNumber").toString())));
						}
						// 如果不是帘头尺寸的话
						if (goodSpecial.getType() != 2 && goodSpecial.getType() != 3) {
							goodSpecial.setPanzhuangfangshi(goodSpecialDetailMap.get("panzhuangfangshi")==null?"":
								goodSpecialDetailMap.get("panzhuangfangshi").toString());
						}
						
						// 如果不是帘头尺寸的话
						if (goodSpecial.getType() != 2 && goodSpecial.getType() != 3) {
							goodSpecial.setPinstallSite(goodSpecialDetailMap.get("pinstallSite")==null?"":
								goodSpecialDetailMap.get("pinstallSite").toString());
						}
					}
					goodSpecial.setGoodSpecialTypeStr(CurtainGoodSpecialType.getName(goodSpecial.getType() + 1));
					if (goodSpecial.getGoodForRoom() == null || goodSpecial.getGoodForRoom() == "") {
						goodSpecial.setGoodForRoom(good.getOtherRoom());
					}
					goodSpecial.setGood(good);
			}
			// 根据good查询出配件信息
			collapseNumbers.add(currentGoodSpecials.size());
			goodSpecials.addAll(currentGoodSpecials);
		}
		retMap.put("installIndentGoods", goodSpecials);
		retMap.put("collapseNumbers", collapseNumbers);
		return retMap;
	}
}
